$(function() {
	// 初始化时间
	sys.daterangepicker({
		id : 'salesTime',
		type : 'date',
		// startDate: moment().subtract(2, "days"),
		maxDate : '2099-12-31'
	});
	$("#salesTime").val("");
	
	sys.daterangepicker({
		id : 'registeTime',
		type : 'date',
		// startDate: moment().subtract(2, "days"),
		maxDate : '2099-12-31'
	});
	$("#registeTime").val("");
	
	
	sys.daterangepicker({
		id : 'loginTime',
		type : 'date',
		// startDate: moment().subtract(2, "days"),
		maxDate : '2099-12-31'
	});
	$("#loginTime").val("");
	
	sys.daterangepicker({
		id : 'pcLoginTime',
		type : 'date',
		// startDate: moment().subtract(2, "days"),
		maxDate : '2099-12-31'
	});
	$("#pcLoginTime").val("");
	
	sys.daterangepicker({
		id : 'wxLoginTime',
		type : 'date',
		// startDate: moment().subtract(2, "days"),
		maxDate : '2099-12-31'
	});
	$("#wxLoginTime").val("");
	
	//初始化查询条件中的三级联动
	sys.threeLevelArea({
		provinceId : 'provinceId',
		cityId : 'cityId',
		areaId : 'areaId',
		defaultAll : true
	});
	// 客户等级下拉框
	sys.selectpicker({
		id : 'customerLevel',
		url : rootPath + '/customerLevel/listCustomerLevel',
		valueField : 'id',
		textField : 'levelName',
		defaultAll : true
	})
	
	// 付款方式
	sys.selectpicker({
		id : 'allowedPayType',
        url : rootPath + "/dict/listKeyMapEntites",
        param : {
            keyType : 'payModel'
        },
        valueField : 'keyValue',
        textField : 'keyIntro',
        defaultAll : true
	})
	
	$.ajax({
		type:'POST',
		url: rootPath + '/dict/listKeyMapEntites',
		data : { keyType : "salesmanRoleId" },
		dataType: 'json',
		success: function(data) {  
			if (data.success == '1' && data.data.length > 0) {
				sys.selectpicker({
					id : 'salesmanCode',
					url : rootPath + '/user/getSalesmanList',
					param: {roleId: data.data[0].keyValue},
					valueField : 'id',
					textField : 'userName',
					defaultValue : $('#salesmanCode').attr('init-value'),
					defaultAll: true,
					defaultAllText: '请选择'
				})
			}
		}
	})
	// 客户类型下拉框
	/*
	 * sys.selectpicker({ id: 'customerType', url: rootPath +
	 * '/customerType/listCustomerType', valueField: 'id', textField:
	 * 'typeName', defaultAll: true })
	 */
	// 合作汇总下拉框
	sys.selectpicker({
		id : 'coperateFlag',
		url : rootPath + '/dict/listKeyMapEntites',
		param : {
			keyType : "coperateFlag"
		},
		valueField : 'keyValue',
		textField : 'keyIntro',
		defaultAll : true
	})
		
	initCompanyGrid();
	
	// 查询
	$('#btnQuery').on('click', function() {
		sys.reloadTable('companyTable');
	});
	
	// 清空
	$('#btnClear').on('click', function() {
		$("#customerName").val("");
		$("#companyName").val("");
		/*$("#customerType").selectpicker('val', "");*/
		$("#customerLevel").selectpicker('val', "");
		$("#coperateFlag").selectpicker('val', "");
		$("#salesmanCode").selectpicker('val', "");
		$("#mobile").val("");
		$("#provinceId").selectpicker('val', "");
		$("#cityId").selectpicker('val', "");
		$("#areaId").selectpicker('val', "");
		$("#allowedPayType").selectpicker('val', "");
		$("#registeTime").val("");
		$("#salesTime").val("");
		$("#loginTime").val("");
		$("#pcLoginTime").val("");
		$("#wxLoginTime").val("");
	});
	
	//点击跳转到新增客户信息页面
	$('#btnAdd').on('click', function() {
		window.location.href = rootPath + '/company/toAddCompany';
	});
})

/**
 * 初始化用户信息列表
 */
function initCompanyGrid(){
	// 定义列
	var columns = [
   		{ ield : 'no', title : '序号', align : 'left',
   			formatter : function(value, row, index) {
   				return index + 1;
   			}
   		},
   		{ field : 'companyName', title : '单位名称', align : 'center', valign:'middle',
   			formatter : function(value, row, index) {
   				var companyNameHtm = "";
   				if(row.remark) {
   					companyNameHtm = row.companyName + "（" + row.remark + "）";
   				} else {
   					companyNameHtm = row.companyName;
   				}
   				return companyNameHtm;
   			}
   		},
   		{ field : 'customerList', title : '人员信息', align : 'center', valign:'middle', 
   			formatter : function(value, row, index) {
   				var customerDetailHtml = "";
   				if(row.customerList && row.customerList.length > 0){
   					for(var i = 0 ;i < row.customerList.length ; i++ ){
   						var customer = row.customerList[i];
   						customerDetailHtml += "<div><span><a style='color:#0063b1;text-transform:uppercase;' onclick='toEditDetail("+row.id+','+customer.id+")'>"+customer.userName+"</a></span><span style='margin-left:20px;'>"+customer.mobile+"</span></div>";
   					}
   				}
				return customerDetailHtml;
			}},
   		{ field : 'customerLevelInfo.levelName', title : '客户级别', align : 'center', valign:'middle' },
   		/*{ field : 'customerTypeInfo.typeName', title : '客户类型', align : 'center', valign:'middle' },*/
   		{ field : '#', title : '地区', align : 'left',halign:'center',  valign:'middle', 
   			formatter : function(value, row, index) {
   					return formatString(row.provinceName) +
   						formatString(row.cityName) +
   						formatString(row.areaName) +
   						formatString(row.streetName) +
   						formatString(row.address);
   			}
   		},
   		{ field : 'allowedPayType', title : '付款方式', align : 'center', valign:'middle' ,
   			formatter:function(value, row, index){
   				if (value == "01"){
   					return "立即支付";
   				}else if(value == "01,02"){
   					return "货到付款";
   				}
   			}},
   		{ field : 'customerNum', title : '人员数', align : 'center', valign:'middle' },
   		{ field : 'salesmanName', title : '销售经理', align : 'center', valign:'middle' },
   		{ field : 'createTime', title : '注册时间', align : 'center', valign:'middle' ,
   			formatter:function(value, row, index){
   				return formatDateTime(value, row, index);
   			}
   		},
   		{ field : '#', title : '操作', align : 'center', valign:'middle',
   			formatter : function(value, row, index) {
   				var isSalesman = $("#isSalesman").val();
   				var strHtml = "";
   				strHtml += "<a class='btn btn-warning btn-xs' onclick='toEdit("+row.id+")'>编辑</a>";
   				if(isSalesman == '0') {
   					strHtml += "<a class='btn btn-danger btn-xs' onclick='toRemove("+row.id+")'>删除</a>";
   				}
   				return strHtml;
   			}
   		} ];
			
			
	// 定义查询回调函数（查询参数在此设置）
	var queryParams = function(params) {
		
		return {
			rows : params.limit, // 页面大小
			page : params.pageNumber, // 页码 
			"companyName"	: $("#companyName").val(), 
			"salesmanCode"	: $("#salesmanCode").val(),
			"customerLevel"	: $("#customerLevel").val(),
			"coperateFlag"	: $("#coperateFlag").val(),
			"provinceCode"	: $("#provinceId").val(),
			"cityCode"		: $("#cityId").val(),
			"areaCode"		: $("#areaId").val(),
			"userName"		: $("#customerName").val(),
			"mobile"		: $("#mobile").val(),
			"isSalesman"	: $("#isSalesman").val(),
			"allowedPayType": $("#allowedPayType").val(),
			"registeTime"   : $("#registeTime").val(),
			"salesTime"     : $("#salesTime").val(),
			"loginTime"     : $("#loginTime").val(),
			"pcLoginTime"   : $("#pcLoginTime").val(),
			"wxLoginTime"   : $("#wxLoginTime").val()
		};
	};
	
	//var url = rootPath + "/customer/listCustomerPage"; // 请求json数据的服务器地址
	var url = rootPath + "/company/listCompanyPage";
	sys.initTable('companyTable', {
		url : url,
		queryParams : queryParams,
		showColumns : true,
		columns : columns,
		striped : true,
		clickToSelect : true
	});
}

function formatString(str) {
	if (!str) return "";
	return str;
}

/**
 * 跳转编辑页面 
 * id 客户信息主键ID  
 */
function toEdit(id) {
	//window.location.href = rootPath + "/company/toUpdateCompany?id=" + id;
	var index = showRemote(rootPath + "/company/toUpdateCompany?id=" + id, function(){}, {title: '客户信息编辑'});
	layer.full(index);
}

// 跳转编辑页面，默认显示客户编辑选项卡
function toEditDetail(id , customerId) {
	var index = showRemote(rootPath + "/company/toUpdateCompany?id=" + id+"&customerId="+customerId, function(){}, {title: '客户信息编辑'});
	layer.full(index);
}


/**
 * 删除客户信息 
 */
function toRemove(id) {
	var url = rootPath + "/company/removeCompany";
	showConfirm("确定要删除？", function(){
		$.ajax({
			type: 'POST',
			url: url,
			async: false,
			data: {id: id},
			dataType: 'json',
			success: function(data) {
				if (data.code == '1') {
					sys.reloadTable("companyTable");
					showSuccess(data.msg);
				} else {
					showErr(data.msg);
				}
			}
		});
	})
}